package com.qiyu.mq.core.producer;

import com.qiyu.mq.core.config.MQException;
import com.qiyu.mq.core.serializer.Serializer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.stereotype.Component;

/**
 * @author idea
 * @version V1.0
 * @date 2020/8/10
 */
@Component
public class MqProducerTemplate<T> {

    private String topic;

    private String tag;

    private ProducerFactory producerFactory;

    private Serializer serializer;


    public SendResult send(T t) {
        SendResult sendResult = null;
        try {
            sendResult = producerFactory.createProducer().send(createMessage(topic, t));
        } catch (Exception e) {
            throw new MQException(e);
        }
        return sendResult;
    }

    private Message createMessage(String topic, T t) {
        return new Message(topic, serializer.serializer(t));
    }


    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public String getTag() {
        return tag;
    }

    public void setTag(String tag) {
        this.tag = tag;
    }

    public ProducerFactory getProducerFactory() {
        return producerFactory;
    }

    public void setProducerFactory(ProducerFactory producerFactory) {
        this.producerFactory = producerFactory;
    }

    public Serializer getSerializer() {
        return serializer;
    }

    public void setSerializer(Serializer serializer) {
        this.serializer = serializer;
    }
}
